<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 易而优团队 by 陈风任 <491085389@qq.com>
 * Date: 2021-01-14
 */

namespace app\admin\model;
use think\Db;
use think\Page;
use think\Model;
use think\Config;

/**
 * 售后服务数据模型(维权订单数据模型)
 */
load_trait('controller/Jump');

class ShopOrderService extends Model
{
    use \traits\controller\Jump;

    //初始化
    protected function initialize()
    {
        // 需要调用`Model`的`initialize`方法
        parent::initialize();
        // 会员表
        $this->usersDb = Db::name('users');
        // 订单主表
        $this->shopOrderDb = Db::name('shop_order');
        // 订单明细表
        $this->shopOrderDetailsDb = Db::name('shop_order_details');
        // 订单退换明细表
        $this->shopOrderServiceDb = Db::name('shop_order_service');
        // 订单退换服务记录表
        $this->shopOrderServiceLogDb = Db::name('shop_order_service_log');
    }

    // 读取所有退换货服务信息处理返回
    public function getOrderServiceList($isMerchant = false)
    {   
        // 查询条件
        $where = [
            'a.status' => ['NOT IN', [3, 8, 9]],
            'a.merchant_id' => !empty($isMerchant) ? ['>', 0] : 0
        ];

        // 查询类型(3=仅退款；12=换货、退货退款)
        $queryStatus = input('queryStatus/d', 0);
        if (!empty($queryStatus) && 1 === intval($queryStatus)) {
            $where['a.status'] = ['IN', [1]];
        } else if (!empty($queryStatus) && 2 === intval($queryStatus)) {
            $where['a.status'] = ['IN', [2, 4, 5, 6]];
        } else if (!empty($queryStatus) && 3 === intval($queryStatus)) {
            $where['a.status'] = ['IN', [7]];
        }

        // 维权状态查询
        $status = input('status/d', 0);
        if (!empty($status) && 32 === intval($status)) {
            $where['a.status'] = 2;
            $where['a.service_type'] = 3;
        } else if (!empty($status) && 122 === intval($status)) {
            $where['a.status'] = 2;
            $where['a.service_type'] = ['IN', [1, 2]];
        } else if (!empty($status)) {
            $where['a.status'] = intval($status);
        }

        // 关键词查询
        $keywords = input('keywords/s', '');
        $keywords = !empty($keywords) ? trim($keywords) : '';
        if (!empty($keywords)) $where['b.order_code|c.product_name|a.refund_code'] = ['LIKE', "%{$keywords}%"];

        // 售后类型查询
        $service_type = input('service_type/d', 0);
        if (!empty($service_type)) $where['a.service_type'] = intval($service_type);
        
        // 发布时间查询
        $add_time = input('param.add_time/s');
        if (!empty($add_time)) {
            $add_time = explode('~', $add_time);
            $start = strtotime(rtrim($add_time[0]));
            $finish = strtotime(rtrim($add_time[1]).' 23:59:59');
            $where['a.add_time'] = ['between', "$start, $finish"];
        }

        // 分页查询
        $count = $this->shopOrderServiceDb->alias('a')
            ->join('__SHOP_ORDER__ b', 'a.order_id = b.order_id', 'LEFT')
            ->join('__SHOP_ORDER_DETAILS__ c', 'a.details_id = c.details_id', 'LEFT')
            ->where($where)
            ->count('a.service_id');
        $pageObj = new Page($count, config('paginate.list_rows'));

        // 维权列表查询
        if (!empty($isMerchant)) {
            // 多商家查询
            $serviceList = $this->shopOrderServiceDb->alias('a')
                ->field('a.*, b.product_price, b.num, d.merchant_name, c.order_status')
                ->join('__SHOP_ORDER_DETAILS__ b', 'a.details_id = b.details_id', 'LEFT')
                ->join('__SHOP_ORDER__ c', 'a.order_id = c.order_id', 'LEFT')
                ->join('__WEAPP_MULTI_MERCHANT__ d', 'a.merchant_id = d.merchant_id', 'LEFT')
                ->limit($pageObj->firstRow.','.$pageObj->listRows)
                ->where($where)
                ->order('a.add_time desc, a.service_id desc')
                ->select();
        } else {
            // 后台查询
            $field = 'a.*';
            $field .= ', b.order_code, b.order_status, b.consignee, b.mobile, b.province, b.city, b.district, b.address';
            $field .= ', c.product_name, c.product_price, c.num as product_num, c.litpic as product_img, c.data as product_data';
            $serviceList = $this->shopOrderServiceDb->alias('a')
                ->field($field)
                ->join('__SHOP_ORDER__ b', 'a.order_id = b.order_id', 'LEFT')
                ->join('__SHOP_ORDER_DETAILS__ c', 'a.details_id = c.details_id', 'LEFT')
                ->limit($pageObj->firstRow.','.$pageObj->listRows)
                ->where($where)
                ->order('a.add_time desc, a.service_id desc')
                ->select();
        }
        foreach ($serviceList as $key => $value) {
            // 添加时间
            $value['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
            // 商品封面图
            $value['product_img'] = handle_subdir_pic(get_default_pic($value['product_img']));
            // 处理商品规格，组合数据
            $product_data = !empty($value['product_data']) ? unserialize($value['product_data']) : [];
            $productSpec = !empty($product_data['product_spec']) ? explode('；', $product_data['product_spec']) : '';
            $specData = '';
            foreach ($productSpec as $spec) {
                if (!empty($spec)) $specData .= '<span>' . $spec . '</span>';
            }
            $value['product_spec'] = $specData;
            // 覆盖原数据
            $serviceList[$key] = $value;
        }

        $Return['pageObj'] = $pageObj;
        $Return['pageStr'] = $pageObj->show();
        $Return['serviceList'] = $serviceList;

        return $Return;
    }

    // 读取某用户所有仅退款.退货退款的服务信息处理返回
    public function getUsersOrderServiceList($isMerchant = false,$users_id = 0)
    {
        // 维权状态查询
        $where['a.status'] = ['NOT IN', [3,8,9]];
        $where['a.service_type'] = ['IN', [2,3]];
        $where['a.users_id'] = $users_id;

        // 关键词查询
        $keywords = input('keywords/s', '');
        $keywords = !empty($keywords) ? trim($keywords) : '';
        if (!empty($keywords)) $where['a.order_code|c.product_name|a.refund_code'] = ['LIKE', "%{$keywords}%"];


        // 分页查询
        $count = $this->shopOrderServiceDb->alias('a')->where($where)->count('a.service_id');
        $pageObj = new Page($count, config('paginate.list_rows'));

        // 维权列表查询
        if (!empty($isMerchant)) {
            // 多商家查询
            $serviceList = $this->shopOrderServiceDb->alias('a')
                ->field('a.*, b.product_price, b.num, d.merchant_name, c.order_status')
                ->join('__SHOP_ORDER_DETAILS__ b', 'a.details_id = b.details_id', 'LEFT')
                ->join('__SHOP_ORDER__ c', 'a.order_id = c.order_id', 'LEFT')
                ->join('__WEAPP_MULTI_MERCHANT__ d', 'a.merchant_id = d.merchant_id', 'LEFT')
                ->limit($pageObj->firstRow.','.$pageObj->listRows)
                ->where($where)
                ->order('a.add_time desc, a.service_id desc')
                ->select();
        } else {
            // 后台查询
            $field = 'a.*';
            $field .= ', b.order_code, b.order_status, b.consignee, b.mobile, b.province, b.city, b.district, b.address';
            $field .= ', c.product_name, c.product_price, c.num as product_num, c.litpic as product_img, c.data as product_data';
            $serviceList = $this->shopOrderServiceDb->alias('a')
                ->field($field)
                ->join('__SHOP_ORDER__ b', 'a.order_id = b.order_id', 'LEFT')
                ->join('__SHOP_ORDER_DETAILS__ c', 'a.details_id = c.details_id', 'LEFT')
                ->limit($pageObj->firstRow.','.$pageObj->listRows)
                ->where($where)
                ->order('a.add_time desc, a.service_id desc')
                ->select();
        }
        foreach ($serviceList as $key => $value) {
            // 添加时间
            $value['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
            // 商品封面图
            $value['product_img'] = handle_subdir_pic(get_default_pic($value['product_img']));
            // 处理商品规格，组合数据
            $product_data = !empty($value['product_data']) ? unserialize($value['product_data']) : [];
            $productSpec = !empty($product_data['product_spec']) ? explode('；', $product_data['product_spec']) : '';
            $specData = '';
            foreach ($productSpec as $spec) {
                if (!empty($spec)) $specData .= '<span>' . $spec . '</span>';
            }
            $value['product_spec'] = $specData;
            // 覆盖原数据
            $serviceList[$key] = $value;
        }

        $Return['pageObj'] = $pageObj;
        $Return['pageStr'] = $pageObj->show();
        $Return['serviceList'] = $serviceList;

        return $Return;
    }

    public function getOrderServiceDetails($service_id = 0)
    {
        if (empty($service_id)) return [];

        // 查询维权订单
        $service = $this->shopOrderServiceDb->where('service_id', $service_id)->find();
        if (empty($service)) return [];

        // 查询订单信息
        $where = [
            'order_id' => intval($service['order_id']),
        ];
        $order = $this->shopOrderDb->where($where)->find();
        // 订单地址处理
        $provinceText = !empty($order['province']) ? get_province_name($order['province']) : '';
        $cityText = !empty($order['city']) ? get_city_name($order['city']) : '';
        $districtText = !empty($order['district']) ? get_area_name($order['district']) : '';
        $order['address'] = $provinceText . '-' . $cityText . '-' . $districtText . '-' . $order['address'];
        // 订单商家备注次数
        $order['adminNoteCount'] = !empty($order['admin_note']) ? count(unserialize($order['admin_note'])) : 0;
        // 订单支付方式
        $order['pay_name'] = Config::get('global.pay_method_arr')[$order['pay_name']];
        // 订单类型
        $order['prom_type'] = 1 === intval($order['prom_type']) ? '普通订单' : '普通订单';
        // 订单来源
        if (!empty($order['order_terminal']) && 2 === intval($order['order_terminal'])) {
            $order['order_terminal'] = '手机端';
        } else if (!empty($order['order_terminal']) && 3 === intval($order['order_terminal'])) {
            $order['order_terminal'] = '微信小程序';
        } else {
            $order['order_terminal'] = '电脑端';
        }

        // 查询订单商品信息
        $where = [
            'details_id' => intval($service['details_id']),
        ];
        $details = $this->shopOrderDetailsDb->where($where)->find();
        $details['product_img'] = !empty($details['litpic']) ? get_default_pic($details['litpic']) : '';
        $details['product_subtotal'] = sprintf("%.2f", floatval($details['product_price']) * floatval($details['num']));
        // 规格处理
        $detailsData = !empty($details['data']) ? unserialize($details['data']) : [];
        $productSpec = !empty($detailsData['product_spec']) ? explode('；', $detailsData['product_spec']) : '';
        $specData = '';
        foreach ($productSpec as $value) {
            if (!empty($value)) $specData .= '<span>' . $value . '</span>';
        }
        $details['product_spec'] = $specData;

        $refundCoupon = $lastOne = 0;
        // 查询所属订单下有多少个商品
        $where = [
            'users_id' => intval($service['users_id']),
            'order_id' => intval($service['order_id']),
        ];
        $goodsCount = $this->shopOrderDetailsDb->where($where)->count();
        // 查询所属订单下有多少个已完成维权的商品
        $where = [
            'status' => 7,
            'users_id' => intval($service['users_id']),
            'order_id' => intval($service['order_id']),
        ];
        $applyCount = $this->shopOrderServiceDb->where($where)->count();
        // 计算维权是否为本次商品订单中的最后一个维权商品
        $value = intval($goodsCount) - intval($applyCount);

        if (1 === intval($value)) {
            $lastOne = 1;
            // 如果使用优惠券，则检测这个维权订单是否是所属订单中最后一个未完成的维权订单，如果是最后一个则将优惠券退还
            if (!empty($order['use_id']) && !empty($order['coupon_id']) && !empty($order['coupon_price'])) $refundCoupon = 1;
        }

        // 如果是最后一个维权订单则执行
        if (!empty($lastOne)) {
            // 如果使用积分则执行
            if (!empty($order['pay_use_scores_num']) && !empty($service['refund_scores_num'])) {
                // 查询本次商品订单已完成退回的积分数
                $where = [
                    'status' => 7,
                    'users_id' => intval($service['users_id']),
                    'order_id' => intval($service['order_id']),
                ];
                $refundScoresNum = $this->shopOrderServiceDb->where($where)->sum('refund_scores_num');
                $service['refund_scores_num'] = intval($order['pay_use_scores_num']) - intval($refundScoresNum);
            }
        }

        // 信息处理
        $service['add_time'] = date('Y-m-d H:i:s', $service['add_time']);
        $service['upload_img'] = !empty($service['upload_img']) ? explode(',', $service['upload_img']) : [];
        $service['audit_time'] = !empty($service['audit_time']) ? date('Y-m-d H:i:s', $service['audit_time']) : 0;
        $service['update_time'] = !empty($service['update_time']) ? date('Y-m-d H:i:s', $service['update_time']) : 0;
        $service['manual_time'] = !empty($service['manual_time']) ? date('Y-m-d H:i:s', $service['manual_time']) : 0;
        $service['status_text'] = Config::get('global.order_service_status')[$service['status']];
        $service['service_type_text'] = Config::get('global.order_service_type')[$service['service_type']];
        $service['users_delivery'] = !empty($service['users_delivery']) ? unserialize($service['users_delivery']) : [];
        if (!empty($service['users_delivery']['time'])) {
            $service['users_delivery']['time'] = date('Y-m-d H:i:s', $service['users_delivery']['time']);
        }
        $service['admin_delivery'] = !empty($service['admin_delivery']) ? unserialize($service['admin_delivery']) : [];
        if (!empty($service['admin_delivery']['time'])) {
            $service['admin_delivery']['time'] = date('Y-m-d H:i:s', $service['admin_delivery']['time']);
        }
        $service['actual_price'] = floatval($service['actual_price']) > 0 ? floatval($service['actual_price']) : floatval($service['refund_price']);

        // 会员信息
        $users = $this->usersDb->field('users_id, username, nickname, mobile, head_pic, sex')->find($service['users_id']);
        $users['nickname'] = empty($users['nickname']) ? $users['username'] : $users['nickname'];
        $users['head_pic'] = get_head_pic($users['head_pic'], false, $users['sex']);

        // 服务记录表信息
        $serviceLog = $this->shopOrderServiceLogDb->order('log_id asc')->where('service_id', $service['service_id'])->select();
        foreach ($serviceLog as $key => $value) {
            $value['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
            if (!empty($value['users_id'])) {
                $value['log_note'] = '[买家] ' . $value['log_note'];
                if (intval($value['users_id']) === intval($users['users_id'])) {
                    $value['name'] = $users['nickname'];
                } else {
                    $value['name'] = Db::name('users')->where('users_id', $value['users_id'])->getField('username');
                }
            } else if (!empty($value['admin_id'])) {
                $value['log_note'] = '[商家] ' . $value['log_note'];
                $value['name'] = getAdminInfo(session('admin_id'))['user_name'];
            }
            $serviceLog[$key] = $value;
        }
        // dump($serviceLog);exit;
        $processLog = $serviceLog;

        $return['users'] = $users;
        $return['order'] = $order;
        $return['lastOne'] = $lastOne;
        $return['details'] = $details;
        $return['service'] = $service;
        rsort($serviceLog);
        $return['serviceLog'] = $serviceLog;
        $return['processLog'] = $processLog;
        $return['refundCoupon'] = $refundCoupon;
        // dump($return);exit;
        return $return;
    }

    // 售后服务处理(维权订单处理)
    public function afterServiceHandle($post = [])
    {
        // 更新指定的维权订单
        $times = getTime();
        $where = [
            'users_id' => $post['users_id'],
            'order_id' => $post['order_id'],
            'details_id' => $post['details_id'],
            'service_id' => $post['service_id'],
            'product_id' => $post['product_id']
        ];
        $update = [
            'update_time' => $times,
            'status' => intval($post['status'])
        ];
        // 存在商家发货信息则执行
        if (!empty($post['delivery'])) {
            $post['delivery']['time'] = $times;
            $update['admin_delivery'] = serialize($post['delivery']);
        }
        // 存在退款备注则执行
        if (!empty($post['refund_remark'])) {
            $update['refund_remark'] = htmlspecialchars($post['refund_remark']);
        }
        // 同意申请、拒接申请时写入审核时间
        if (in_array($post['status'], [2])) $update['audit_time'] = $times;
        if (in_array($post['status'], [3, 8])) $update['audit_time'] = 0;

        // 执行更新
        $resultID = $this->shopOrderServiceDb->where($where)->update($update);

        // 更新后续操作
        if (!empty($resultID)) {
            // 退款到余额
            if (7 === intval($post['status']) && 1 === intval($post['refund_way']) && in_array($post['service_type'], [2, 3])) {
                // 执行退回余额
                $where = [
                    'users_id' => $post['users_id']
                ];
                $update = [
                    'users_money' => Db::raw('users_money+'.($post['actual_price'])),
                    'update_time' => $times
                ];
                $resultID = $this->usersDb->where($where)->update($update);
                if (!empty($resultID)) {
                    if (empty($post['order_code'])) {
                        $post['order_code'] = $this->shopOrderDb->where('order_id', $post['order_id'])->getField('order_code');
                    }
                    // 添加余额记录
                    usersMoneyRecording($post['order_code'], $post, $post['actual_price'], '商品退款维权结束');
                }

                // 执行退回积分
                $where = [
                    'users_id' => $post['users_id']
                ];
                $update = [
                    'scores' => Db::raw('scores+'.($post['refund_scores_num'])),
                    'update_time' => $times
                ];
                $resultID = $this->usersDb->where($where)->update($update);
                if (!empty($resultID)) {
                    // if (empty($post['order_code'])) {
                    //     $post['order_code'] = $this->shopOrderDb->where('order_id', $post['order_id'])->getField('order_code');
                    // }
                    // 添加积分记录
                    $insert = [
                        'type' => 11,
                        'users_id' => $post['users_id'],
                        'score' => $post['refund_scores_num'],
                        'info' => '订单退回对应积分',
                        'remark' => '订单退回对应积分',
                    ];
                    eyou_give_score($insert, 2, false);
                }

                // 还原优惠券
                if (!empty($post['refund_coupon']) && !empty($post['use_id'])) {
                    $where = [
                        'use_id' => $post['use_id']
                    ];
                    $couponUse = Db::name('shop_coupon_use')->where($where)->find();
                    if (!empty($couponUse)) {
                        $where = [
                            'use_id' => $post['use_id'],
                            'users_id' => $post['users_id']
                        ];
                        $update = [
                            'use_time' => 0,
                            'update_time' => $times
                        ];
                        if ($couponUse['start_time'] <= $times && $couponUse['end_time'] >= $times) {
                            $update['use_status'] = 0;
                        } else {
                            $update['use_status'] = 2;
                        }
                        Db::name('shop_coupon_use')->where($where)->update($update);
                    }
                }

                // 恢复库存
                model('ShopGoods')->goodsStockRestore($post['order_id'], $post['users_id'], $post['details_id']);
            }

            // 拒接申请、关闭维权时更新订单商品为可申请售后
            if (in_array($post['status'], [3, 8, 9])) {
                $where = [
                    'users_id' => $post['users_id'],
                    'order_id' => $post['order_id'],
                    'details_id' => $post['details_id'],
                    'product_id' => $post['product_id']
                ];
                $update = [
                    'apply_service' => 0,
                    'update_time' => $times
                ];
                $this->shopOrderDetailsDb->where($where)->update($update);
            }

            // 如果维权结束且最后一个维权订单则将订单更新为已关闭(仅针对待发货和待收货的订单，已完成订单不做处理)
            if (7 === intval($post['status']) && !empty($post['lastOne']) && in_array($post['order_status'], [1, 2])) {
                $where = [
                    'users_id' => $post['users_id'],
                    'order_id' => $post['order_id'],
                ];
                $update = [
                    'update_time' => $times,
                    'order_status' => -1,
                ];
                $isUpdate = Db::name('shop_order')->where($where)->update($update);
                if (!empty($isUpdate)) {
                    // 添加订单操作记录
                    AddOrderAction($post['order_id'], 0, session('admin_id'), -1, 1, 1, '订单关闭', '维权完成，订单自动关闭！');
                }
            }

            // 维权记录
            $this->addOrderServiceLog($post);

            $this->success('操作成功！', url('ShopService/after_service'));
        } else {
            $this->error('操作失败！');
        }
    }

    // 记录商品退换货服务单信息
    public function addOrderServiceLog($post = [])
    {
        if (empty($post)) return false;
        // 维权类型
        $service_type = '';
        if (!empty($post['service_type']) && 1 === intval($post['service_type'])) {
            $service_type = '换货';
        } else if (!empty($post['service_type']) && 2 === intval($post['service_type'])) {
            $service_type = '退货退款';
        } else if (!empty($post['service_type']) && 3 === intval($post['service_type'])) {
            $service_type = '退款';
        }
        // 操作事由
        if (2 === intval($post['status'])) {
            $logNote = '同意' . $service_type . '申请！';
        } else if (3 === intval($post['status'])) {
            $logNote = '拒绝' . $service_type . '申请！';
        } else if (4 === intval($post['status'])) {
            $logNote = '已退货，商家待收货！';
        } else if (5 === intval($post['status']) && 1 === intval($post['service_type'])) {
            $logNote = '已收到退货，待重新发货！';
        } else if (5 === intval($post['status']) && 2 === intval($post['service_type'])) {
            $logNote = '已收到退货，待转账！';
        } else if (6 === intval($post['status'])) {
            $logNote = '已重新发货，买家待收货！';
        } else if (7 === intval($post['status']) && 1 === intval($post['service_type'])) {
            $logNote = '买家已确认收货，' . $service_type . '维权完成！';
        } else if (7 === intval($post['status']) && in_array($post['service_type'], [2, 3])) {
            $logNote = $service_type . '维权完成！';
        } else if (8 === intval($post['status'])) {
            $logNote = '关闭' . $service_type . '申请！';
        } else if (9 === intval($post['status'])) {
            $logNote = '已拒绝收货，请与买家联系处理！';
        }
        orderServiceLog($post['service_id'], $post['order_id'], 0, session('admin_id'), $logNote);
    }
}